from urllib import request

import requests, time, hashlib, base64, hmac, json
import urllib.parse, os
from rest_framework import viewsets, status, response




class DingDingMessage:
    def __init__(self, access_token, secret_key="<KEY>"):
        self.access_token = access_token
        self.secret_key = secret_key

    def gen_sign(self):
        timestamp = str(round(time.time() * 1000))
        secret = self.secret_key
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        # print(timestamp)
        # print(sign)
        return timestamp, sign

    def send_text(self, msg):
        timestamp, sign = self.gen_sign()
        url = f"https://oapi.dingtalk.com/robot/send?access_token={self.access_token}&timestamp={timestamp}&sign={sign}"
        headers = {'Content-Type': 'application/json;charset=UTF-8'}
        request_param = {
            "msgtype": "text",
            "text": {
                "content": msg
            },
        }
        try:
            response = requests.post(url, data=json.dumps(request_param), headers=headers)
        except Exception as e:
            print(e)

    def send_markdown(self, data):
        timestamp, sign = self.gen_sign()
        url = f"https://oapi.dingtalk.com/robot/send?access_token={self.access_token}&timestamp={timestamp}&sign={sign}"
        headers = {'Content-Type': 'application/json;charset=UTF-8'}
        request_param = {
            "msgtype": "markdown",
            "markdown": {
                "title": "构建通知",
                "text": f"#### 项目：{data["project"]} \n > 分支：{data["branch"]} \\\n > TAG：{data["tag"]} \\\n > 结果：{data["result"]} \n"
            }
        }
        try:
            response = requests.post(url, data=json.dumps(request_param), headers=headers)
        except Exception as e:
            # print(e)
            return str(e)

        return "发送成功"


def ddSend():
    # dd = DingDingMessage("bbeb8d4beaaa35c780016cc06c4724eeea5888efcc232903e20e331de7104787","SEC84ddcec6e608c10e9cced5bb3299173af36dfea0d37655055509188a9faa61e1")
    dd = DingDingMessage(os.getenv("DD_ACCESS_TOKEN"), os.getenv("DD_SECRET_KEY"))
    # print("DD_ACCESS_TOKEN:", dd.access_token, "DD_SECRET_KEY:", dd.secret_key)
    return dd


class DdMsg(viewsets.ViewSet,
            viewsets.mixins.ListModelMixin,
            viewsets.mixins.RetrieveModelMixin,
            viewsets.mixins.CreateModelMixin,
            viewsets.mixins.UpdateModelMixin, ):

    def create(self, request, *args, **kwargs):
        data = request.data
        # print(data)
        if 'app' in data and 'type' in data and 'msg' in data:
            result = self.MarkDownFromJenkins(data['msg'])
            return response.Response({"msg": result}, status=status.HTTP_200_OK)

        if 'msg' not in data:
            return response.Response({"msg": "缺少 'msg' key"}, status=status.HTTP_400_BAD_REQUEST)
        try:
            ddSend().send_text(data['msg'])
        except Exception as e:
            ddSend().send_text(str(e))
            return response.Response({"msg": str(e)}, status=status.HTTP_400_BAD_REQUEST)
        return response.Response({"msg": data['msg']}, status=status.HTTP_200_OK)

    def MarkDownFromJenkins(self, data):
        result = ddSend().send_markdown(data)
        return result









